package com.superhelper.receiver.service;

import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.superhelper.common.Consts;
import com.superhelper.common.domain.ele.ElePushEntity;

@Service
public class ElePushValidService {
    private static final Logger log = LoggerFactory.getLogger(ElePushValidService.class);

    @Value("${ele.secret}")
    private String secret;

    public boolean valid(ElePushEntity entity) {
        BeanMap bm = BeanMap.create(entity);
        @SuppressWarnings("unchecked")
        Set<String> st = new TreeSet<String>(bm.keySet());
        StringBuilder sb = new StringBuilder();
        for (String k : st) {
            if ("signature".equalsIgnoreCase(k)) {
                continue;
            }
            sb.append(String.format("%s=%s", k, bm.get(k) + ""));
        }
        sb.append(secret);
        String toBeSign = sb.toString();
        String sign = DigestUtils.md5DigestAsHex(toBeSign.getBytes(Consts.UTF8_CHARSET));
        log.info("toBeSign:{}, mySign:{},comeSign:{}", toBeSign, sign, entity.getSignature());
        return StringUtils.equalsIgnoreCase(entity.getSignature(), sign);
    }

    public static void main(String[] args) {
        ElePushEntity entity = new ElePushEntity();
        entity.setAppId(1L);
        entity.setMessage("message");
        entity.setRequestId("reqId1");
        entity.setShopId(2l);
        entity.setSignature("xxxxxxxx");
        entity.setTimestamp(3L);
        entity.setType(4);
        entity.setUserId(5L);
        BeanMap bm = BeanMap.create(entity);
        @SuppressWarnings("unchecked")
        Set<String> st = new TreeSet<String>(bm.keySet());
        for (String k : st) {
            System.out.println(k + ": " + bm.get(k) + "=====" + String.format("%s=%s", k, bm.get(k) + ""));

        }
    }
}
